package com.qf.hytrix.service;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.qf.service.Book;
import org.springframework.web.client.RestTemplate;

/**
 * @Auther: Song
 * @Date: 2022-03-18 18:34
 */
public class HelloCommand2 extends HystrixCommand<String> {
    RestTemplate restTemplate;
    Integer id;

    public HelloCommand2(RestTemplate restTemplate,Integer id) {
        //开启一个名为zhangsan的子线程
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("zhangsan")));
        this.restTemplate = restTemplate;
        this.id = id;
    }

    /**
     *  发起请求的地方
     * @return
     * @throws Exception
     */
    @Override
    protected String run() throws Exception {
//        int i = 1 / 0;
        Book book = restTemplate.getForObject("http://storage/book/?id={1}", Book.class, id);
        System.out.println("book = " + book);
        return "aaa";
    }

    @Override
    protected String getCacheKey() {
        return String.valueOf(id);
    }

    /**
     * 降级服务的地方
     * @return
     */
    @Override
    protected String getFallback() {
        //获取执行时的异常（即 run 方法抛出的异常）
        Throwable throwable = getExecutionException();
        return "error---fallback--->" + throwable;
    }
}
